package com.bilibili.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bilibili.dao.VideoCollectionMapper;
import com.bilibili.domain.entity.Video;
import com.bilibili.domain.entity.VideoCollection;
import com.bilibili.domain.entity.VideoLike;
import com.bilibili.domain.exception.ConditionException;
import com.bilibili.service.VideoCollectionService;
import com.bilibili.service.VideoService;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* @author www
* @description 针对表【t_video_collection(视频收藏记录表)】的数据库操作Service实现
* @createDate 2024-06-17 16:03:46
*/
@Service
public class VideoCollectionServiceImpl extends ServiceImpl<VideoCollectionMapper, VideoCollection>
    implements VideoCollectionService {

    @Resource
    private VideoCollectionMapper videoCollectionMapper;
    @Resource
    private VideoService videoService;

    LambdaQueryWrapper<VideoCollection> wrapper = new LambdaQueryWrapper<>();

    @Override
    public void addVideoCollection(VideoCollection videoCollection, Long userId) {
        Long videoId = videoCollection.getVideoId();
        Long groupId = videoCollection.getGroupId();

        if (videoId==null||groupId==null){
            throw new ConditionException("参数异常！");
        }
        Video video = videoService.getById(videoId);
        if (video==null){
            throw new ConditionException("非法视频！");
        }

        //删除原有视频收藏
        wrapper.eq(VideoCollection::getVideoId,videoId)
                .eq(VideoCollection::getUserId,userId);
        videoCollectionMapper.delete(wrapper);
        //添加新的视频收藏
        videoCollection.setUserId(userId);
        videoCollection.setCreateTime(new Date());
        videoCollectionMapper.insert(videoCollection);
    }

    @Override
    public void deleteVideoCollection(Long videoId, Long userId) {
        wrapper.eq(VideoCollection::getVideoId,videoId)
                .eq(VideoCollection::getUserId,userId);
        videoCollectionMapper.delete(wrapper);
    }

    @Override
    public Map<String, Object> getVideoCollection(Long videoId, Long userId) {
        wrapper.eq(VideoCollection::getVideoId,videoId);
        Long count = videoCollectionMapper.selectCount(wrapper);

        //查询该登录用户是否对该视频收藏
        wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VideoCollection::getVideoId,videoId)
                .eq(VideoCollection::getUserId,userId);
        VideoCollection videoCollection = videoCollectionMapper.selectOne(wrapper);

        boolean collection = videoCollection!=null?true:false;
        Map<String,Object> map = new HashMap<>();
        map.put("count",count);
        map.put("collection",collection);

        return map;
    }
}




